package com.luck.util;

import com.google.zxing.common.BitMatrix;
import lombok.extern.slf4j.Slf4j;
import sun.misc.BASE64Encoder;

import java.io.*;

@Slf4j
public class FileImgUtil {

    /**
     * 将图片转为base64字符串
     * @param imgFile
     * @return
     */
    public static byte[] imageToBytes(String imgFile) {
        InputStream in;
        byte[] data = null;

        // 读取图片字节数组
        try {
            in = new FileInputStream(imgFile);

            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }// 返回Base64编码过的字节数组字符串
        return data;
    }

    /**
     * byte[] -> base64
     * @param bytes   图片bytes
     * @return String 图片base64
     */
    public static String bytesToBASE64String(byte[] bytes) {
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encodeBuffer(bytes).trim();
    }

    /**
     * byte[] -> file
     * @param bytes    图片bytes
     * @param filePath 图片路径+图片名
     * @return
     */
    public static String bytesCreateFile(byte[] bytes, String filePath) {
        File file = new File(filePath + ".png");
        OutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream(file);
            outputStream.write(bytes);
            outputStream.flush();
        } catch (Exception e) {
            log.info("将图片保存到 filePath:{} 失败.", filePath);
            return "fail";
        } finally {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "ok";
    }

    public static void main(String[] args) {
        String s1 = bytesToBASE64String(imageToBytes("D://a.png"));
        System.out.println(s1);
    }

}
